// 简单的本地服务器脚本，用于避免CORS问题
// 使用方法: node server.js

const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const url = require('url');

const PORT = 8081;

// MIME类型映射
const MIME_TYPES = {
  '.html': 'text/html',
  '.js': 'text/javascript',
  '.css': 'text/css',
  '.json': 'application/json',
  '.png': 'image/png',
  '.jpg': 'image/jpg',
  '.gif': 'image/gif',
  '.svg': 'image/svg+xml',
  '.wav': 'audio/wav',
  '.mp4': 'video/mp4',
  '.woff': 'application/font-woff',
  '.ttf': 'application/font-ttf',
  '.eot': 'application/vnd.ms-fontobject',
  '.otf': 'application/font-otf',
  '.wasm': 'application/wasm'
};

// 允许的来源列表
const ALLOWED_ORIGINS = [
  'http://localhost:8080',
  'http://127.0.0.1:8080',
  'http://cloudfactory.me'
];

// 创建服务器
const server = http.createServer((req, res) => {
  console.log(`请求: ${req.method} ${req.url} 来自 ${req.headers.origin || '未知来源'}`);
  
  // 解析URL
  const parsedUrl = url.parse(req.url, true);
  
  // 获取请求来源
  const origin = req.headers.origin || '*';
  
  // 设置CORS头以允许跨域请求
  if (ALLOWED_ORIGINS.includes(origin) || origin === '*') {
    res.setHeader('Access-Control-Allow-Origin', origin);
  } else {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
  }
  
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  
  // 处理预检请求
  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
  }
  
  // 处理百度OCR API代理请求
  if (parsedUrl.pathname === '/api/baidu-ocr/token' && req.method === 'POST') {
    handleBaiduTokenRequest(req, res);
    return;
  }
  
  if (parsedUrl.pathname === '/api/baidu-ocr/recognize' && req.method === 'POST') {
    handleBaiduOCRRequest(req, res);
    return;
  }
  
  // 处理静态文件请求
  handleStaticFileRequest(req, res);
});

// 处理百度OCR令牌请求
function handleBaiduTokenRequest(req, res) {
  let body = '';
  req.on('data', chunk => {
    body += chunk.toString();
  });
  
  req.on('end', () => {
    // 转发请求到百度OCR API
    const options = {
      hostname: 'aip.baidubce.com',
      port: 443,
      path: '/oauth/2.0/token',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(body)
      }
    };
    
    const proxyReq = https.request(options, proxyRes => {
      let proxyBody = '';
      proxyRes.on('data', chunk => {
        proxyBody += chunk;
      });
      
      proxyRes.on('end', () => {
        // 设置响应头
        res.setHeader('Content-Type', 'application/json');
        res.statusCode = proxyRes.statusCode;
        res.end(proxyBody);
      });
    });
    
    proxyReq.on('error', error => {
      console.error('代理请求错误:', error);
      res.statusCode = 500;
      res.end(JSON.stringify({ error: '代理请求失败' }));
    });
    
    // 发送请求体
    proxyReq.write(body);
    proxyReq.end();
  });
}

// 处理百度OCR识别请求
function handleBaiduOCRRequest(req, res) {
  let body = '';
  req.on('data', chunk => {
    body += chunk.toString();
  });
  
  req.on('end', () => {
    // 解析查询参数获取access_token
    const parsedUrl = url.parse(req.url, true);
    const accessToken = parsedUrl.query.access_token;
    
    if (!accessToken) {
      res.statusCode = 400;
      res.end(JSON.stringify({ error: '缺少access_token参数' }));
      return;
    }
    
    // 转发请求到百度OCR API
    const options = {
      hostname: 'aip.baidubce.com',
      port: 443,
      path: `/rest/2.0/ocr/v1/numbers?access_token=${accessToken}`,
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(body)
      }
    };
    
    const proxyReq = https.request(options, proxyRes => {
      let proxyBody = '';
      proxyRes.on('data', chunk => {
        proxyBody += chunk;
      });
      
      proxyRes.on('end', () => {
        // 设置响应头
        res.setHeader('Content-Type', 'application/json');
        res.statusCode = proxyRes.statusCode;
        res.end(proxyBody);
      });
    });
    
    proxyReq.on('error', error => {
      console.error('代理请求错误:', error);
      res.statusCode = 500;
      res.end(JSON.stringify({ error: '代理请求失败' }));
    });
    
    // 发送请求体
    proxyReq.write(body);
    proxyReq.end();
  });
}

// 处理静态文件请求
function handleStaticFileRequest(req, res) {
  // 处理根路径请求
  let filePath = '.' + req.url;
  if (filePath === './') {
    filePath = './index.html';
  }
  
  // 获取文件扩展名
  const extname = String(path.extname(filePath)).toLowerCase();
  const contentType = MIME_TYPES[extname] || 'application/octet-stream';
  
  // 读取文件
  fs.readFile(filePath, (error, content) => {
    if (error) {
      if (error.code === 'ENOENT') {
        // 文件未找到
        fs.readFile('./404.html', (err, content404) => {
          if (err) {
            res.writeHead(404);
            res.end('404: 页面未找到');
          } else {
            res.writeHead(404, { 'Content-Type': 'text/html' });
            res.end(content404, 'utf-8');
          }
        });
      } else {
        // 服务器错误
        res.writeHead(500);
        res.end(`服务器错误: ${error.code}`);
      }
    } else {
      // 成功读取文件
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf-8');
    }
  });
}

// 启动服务器
server.listen(PORT, () => {
  console.log(`服务器正在运行: http://localhost:${PORT}`);
  console.log('允许的来源:', ALLOWED_ORIGINS.join(', '));
  console.log('按 Ctrl+C 停止服务器');
});